package main

import (
	"fmt"
	"io/ioutil"

	"github.com/golang/snappy"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

type User struct {
	ID   int
	Text []byte `gorm:"type:blob"`
}

var mysql *gorm.DB

func init() {
	var err error
	mysql, err = gorm.Open("mysql", "root:nikki@(127.0.0.1:3306)/test?timeout=5s&parseTime=true&loc=Local&charset=utf8")
	if err != nil {
		panic(err)
	}

	mysql.AutoMigrate(&User{})
}

func main() {
	text, err := ioutil.ReadFile("text")
	if err != nil {
		panic(err)
	}
	fmt.Println("Text Size:", len(text))

	{
		u := &User{ID: 1}
		u.Text = snappy.Encode(nil, text)
		if err := mysql.Create(u).Error; err != nil {
			panic(err)
		}
	}
	{
		u := &User{ID: 1}
		if err := mysql.First(u).Error; err != nil {
			panic(err)
		}
		fmt.Println("Text snappy Size:", len(u.Text))
		textRead, err := snappy.Decode(nil, u.Text)
		if err != nil {
			panic(err)
		}
		if string(text) != string(textRead) {
			panic("unexpected")
		}
		fmt.Println("Text snappy Decode Size:", len(textRead))
		fmt.Println("Text snappy:", float32(len(textRead))/float32(len(u.Text)))
		if err := mysql.Delete(u).Error; err != nil {
			panic(err)
		}
	}
}
